package com.jt.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

import java.lang.annotation.Target;

public class ObjectMapperUtil {
    //定义常量对象，
    //优势1：对象独一份节省空间
    //优势2：对象不允许别人随意篡改
    private static final ObjectMapper MAPPER = new ObjectMapper();
    //1.将任意对象转化为json
    public static String toJson(Object object){
        try {
            if (object==null) {
                throw new RuntimeException("传递的参数object为null，请认真检查");
            }
            return MAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            //应该将检查的异常转化为运行时异常
            throw new RuntimeException("传递的对象不支持json转换，检查是否有get，set方法");
        }
    }

    //2.将任意的json串转化为对象，传递什么类型的转换对象
    public static <T> T toObject(String json, Class<T> target){
        if (StringUtils.isEmpty(json)||target == null){
            throw new RuntimeException("传递的参数不能为空");
        }
        try {
            return MAPPER.readValue(json,target);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException("json转换出现异常，参数可能不支持转换");
        }
    }
}
